package com.laikan.library.components;

import android.app.Application;
import android.net.Uri;
import android.support.multidex.MultiDex;
import android.text.TextUtils;
import com.facebook.binaryresource.BinaryResource;
import com.facebook.binaryresource.FileBinaryResource;
import com.facebook.cache.common.CacheKey;
import com.facebook.drawee.backends.pipeline.Fresco;
import com.facebook.drawee.backends.pipeline.PipelineDraweeController;
import com.facebook.drawee.controller.BaseControllerListener;
import com.facebook.drawee.view.SimpleDraweeView;
import com.facebook.imagepipeline.cache.DefaultCacheKeyFactory;
import com.facebook.imagepipeline.common.ResizeOptions;
import com.facebook.imagepipeline.core.ImagePipelineFactory;
import com.facebook.imagepipeline.request.BasePostprocessor;
import com.facebook.imagepipeline.request.ImageRequest;
import com.facebook.imagepipeline.request.ImageRequestBuilder;
import com.laikan.library.helpers.BasicEvent;
import com.laikan.library.httpvolley.engine.HttpApiRequestEngine;
import com.laikan.library.managers.ToastMgr;
import com.laikan.library.utils.DeviceUtil;
import com.socks.library.KLog;
import org.greenrobot.eventbus.EventBus;

import java.io.File;

public class BasicApplication extends Application {

    private static BasicApplication instance;
    public static boolean IS_RELEASE;

    public static BasicApplication getInstance() {

        return instance;
    }

    @Override
    public void onCreate() {

        super.onCreate();
        KLog.e(getClass().getSimpleName() + "    onCreate!!");
        IS_RELEASE = !DeviceUtil.getMetaDataStringValue(this, "UMENG_CHANNEL").equals("test");
        instance = this;
        initApp();
    }

    private void initApp() {
        ToastMgr.getInstance().init(this);
        HttpApiRequestEngine.getInstance().init(getApplicationContext());
        MultiDex.install(this);
    }

    public static void postEvent(BasicEvent event) {
        EventBus.getDefault().post(event);
    }

    //    /**
    //     * 初始化操作，建议在子线程中进行
    //     * 添加的依赖：
    //     * compile 'com.facebook.fresco:fresco:0.10.0+'
    //     * compile 'com.facebook.fresco:animated-webp:0.10.0'//加载webp必须添加
    //     * compile 'com.facebook.fresco:animated-gif:0.10.0' //加载gif必须添加
    //     *
    //     * @param context
    //     * @param cacheSizeInM 磁盘缓存的大小，以M为单位
    //     */
    //    public static void init(final Context context, int cacheSizeInM) {
    //
    //        DiskCacheConfig diskCacheConfig = DiskCacheConfig.newBuilder(context)
    //            .setMaxCacheSize(cacheSizeInM * 1024 * 1024)//最大缓存
    //            .setBaseDirectoryName(PHOTO_FRESCO)//子目录
    //            .setBaseDirectoryPathSupplier(new Supplier<File>() {
    //                @Override
    //                public File get() {
    //                    return context.getCacheDir();//还是推荐缓存到应用本身的缓存文件夹,这样卸载时能自动清除,其他清理软件也能扫描出来
    //                }
    //            })
    //            .build();
    //        MyImageCacheStatsTracker imageCacheStatsTracker = new MyImageCacheStatsTracker();//缓存的监听接口,其方法空实现即可
    //        ImagePipelineConfig config = ImagePipelineConfig.newBuilder(context)
    //            .setMainDiskCacheConfig(diskCacheConfig)
    //            .setImageCacheStatsTracker(imageCacheStatsTracker)
    //            .setDownsampleEnabled(true)
    //            //Downsampling，要不要向下采样,它处理图片的速度比常规的裁剪scaling更快，
    //            // 并且同时支持PNG，JPG以及WEP格式的图片，非常强大,与ResizeOptions配合使用
    //            .setBitmapsConfig(Bitmap.Config.RGB_565)
    //            //如果不是重量级图片应用,就用这个省点内存吧.默认是RGB_888
    //            .build();
    //        Fresco.initialize(context, config);
    //    }

    public static void load(Uri uri, SimpleDraweeView draweeView, BasePostprocessor processor, int width, int height, BaseControllerListener listener) {
        ImageRequest request = ImageRequestBuilder.newBuilderWithSource(uri)
            .setPostprocessor(processor)
            .setResizeOptions(new ResizeOptions(width, height))
            //缩放,在解码前修改内存中的图片大小, 配合Downsampling可以处理所有图片,否则只能处理jpg,
            // 开启Downsampling:在初始化时设置.setDownsampleEnabled(true)
            .setProgressiveRenderingEnabled(true)//支持图片渐进式加载
            .setAutoRotateEnabled(true) //如果图片是侧着,可以自动旋转
            .build();

        PipelineDraweeController controller = (PipelineDraweeController)Fresco.newDraweeControllerBuilder()
            .setImageRequest(request)
            .setControllerListener(listener)
            .setOldController(draweeView.getController())
            .setAutoPlayAnimations(true) //自动播放gif动画
            .build();

        draweeView.setController(controller);
    }

    public static File getFileFromDiskCache(String url) {
        File localFile = null;
        if (!TextUtils.isEmpty(url)) {
            CacheKey cacheKey = DefaultCacheKeyFactory.getInstance().getEncodedCacheKey(ImageRequest.fromUri(url));
            if (ImagePipelineFactory.getInstance().getMainDiskStorageCache().hasKey(cacheKey)) {
                BinaryResource resource = ImagePipelineFactory.getInstance().getMainDiskStorageCache().getResource(cacheKey);
                localFile = ((FileBinaryResource)resource).getFile();
            }else if (ImagePipelineFactory.getInstance().getSmallImageDiskStorageCache().hasKey(cacheKey)) {
                BinaryResource resource = ImagePipelineFactory.getInstance().getSmallImageDiskStorageCache().getResource(cacheKey);
                localFile = ((FileBinaryResource)resource).getFile();
            }
        }
        return localFile;
    }
}
